package com.it.data.manager

import com.it.common.Constants
import com.it.common.utils.LogUtil
import com.it.data.network.interceptor.NetworkInterceptor
import com.it.data.network.interceptor.TokenReqInterceptor
import com.it.data.network.interceptor.TokenResInterceptor
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.Cache
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import okio.IOException
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.io.File
import java.io.FileOutputStream
import java.util.concurrent.TimeUnit

/**
 *  @Description：http管理器
 *  @author：weishixiong
 *  @date：2023/4/18 17:44
 *
 */
object HttpManager {
    private var retrofit: Retrofit? = null
    const val TAG = "HttpManager"

    object MoshiClient {
        val moshi: Moshi = Moshi.Builder()
            .add(KotlinJsonAdapterFactory())
            .build()
    }

    //---------------------------------OkHttp-------------------------------
    private val okClient by lazy {
        OkHttpClient.Builder()
            .cache(Cache(AppManager.appContext.cacheDir, 100 * 1024 * 1024))
            //连接超时时间16S
            .connectTimeout(16, TimeUnit.SECONDS)
            .addInterceptor(NetworkInterceptor())
            .addInterceptor(TokenReqInterceptor())
            .addInterceptor(TokenResInterceptor())
            //Log拦截器
            .addInterceptor(HttpLoggingInterceptor {
                LogUtil.d("HttpLoggingInterceptor", "$it")
            }.setLevel(HttpLoggingInterceptor.Level.BODY))


            .build()
    }

    private val okClientDownloader by lazy {
        OkHttpClient.Builder()
            .cache(Cache(AppManager.appContext.cacheDir, 100 * 1024 * 1024))
            //Log拦截器
            .addInterceptor(NetworkInterceptor())
            .build()
    }

    fun <T> create(service: Class<T>): T {
        retrofit = Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .client(okClient)
            .addConverterFactory(MoshiConverterFactory.create(MoshiClient.moshi)) // 使用 MoshiConverterFactory
            .build()
        return retrofit!!.create(service)

    }

    fun downloadFile(url: String, outputPath: String, listener: DownloadListener? = null) {
        LogUtil.d(TAG, "downloadFile: $url and $outputPath")
        val request = Request.Builder().url(url).build()
        val call = okClientDownloader.newCall(request)
        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                listener?.onFail(e.message)
            }

            override fun onResponse(call: Call, response: Response) {
                if (response.isSuccessful) {
                    val contentLength = response.body?.contentLength() ?: -1
                    val inputStream = response.body?.byteStream()
                    val fos = FileOutputStream(File(outputPath))
                    val buf = ByteArray(1024)
                    var length = 0
                    var progress = 0L
                    while (true) {
                        length = (inputStream?.read(buf) ?: -1)
                        if (length != -1) {
                            fos.write(buf, 0, length.toInt())
                            progress += length
                            listener?.onProgress(progress, contentLength)
                        } else {
                            fos.close()
                            inputStream?.close()
                            listener?.onSuccess(outputPath)
                            break
                        }
                    }
                } else {
                    listener?.onFail("下载失败")
                }
            }
        })
    }

    interface DownloadListener {
        fun onProgress(progress: Long, total: Long)
        fun onSuccess(filePath: String)
        fun onFail(msg: String?)
    }


}